package hong.jun.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 说明:
 * Created on 2023/10/24 15:13
 *
 * @author yanghongjun <1737619387@qq.com>
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {

        List<CompletableFuture<Object>> collect = new ArrayList<>();
        Data data = new Data();
        for (int i = 0; i < 20000; i++) {
            Thread thread = new Thread(() -> add(data));
            //CompletableFuture<Void> future = CompletableFuture.runAsync(() -> thread.run(), Executors.newVirtualThreadPerTaskExecutor());//虚拟线程池
            CompletableFuture<Void> future = CompletableFuture.runAsync(thread, Executors.newVirtualThreadPerTaskExecutor());//虚拟线程池
            CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(future);
            collect.add(objectCompletableFuture);
        }
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(collect.toArray(new CompletableFuture[0]));//列表里所有线程执行完才放行
        voidCompletableFuture.join();
        System.out.println("加锁结果:" + data.getCount());
        System.out.println("CAS结果:" + data.getCount1());
        System.out.println("普通结果:" + data.getCount2());

        /*LockData lockData = new LockData();
        try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 30; i++) {
                //读写锁方案
                executorService.submit(new ThreadLockTask(lockData));
            }
        }*/
    }

    public static void add(Data data) {
        data.add();//加锁
        data.add1();//CAS无锁方案
        data.add2();//普通
    }
}
